﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Reflection;
using Gigya.Socialize.SDK;
using PBDesk.Utilities;

namespace PBDesk.Business.Gigya
{
    public class GigyaHelper
    {

        public static GigyaUser GetGigyaUserFromCookies(NameValueCollection cookieCollection)
        {
            GigyaUser gUser = null;
            try
            {
                if (cookieCollection != null && cookieCollection.Count > 0)
                {
                    PropertyInfo[] properties = typeof(GigyaUser).GetProperties();
                    gUser = new GigyaUser();
                    foreach (PropertyInfo property in properties)
                    {
                        property.SetValue(gUser, cookieCollection[property.Name], null);
                    }
                }
            }
            catch (Exception ex)
            {
                //
            }
            return gUser;
        }
        public static GigyaUser GetGigyaUserFromQS(NameValueCollection queryString)
        {
            GigyaUser gUser = null;
            try
            {
                if (queryString != null && queryString.Count > 0)
                {
                    PropertyInfo[] properties = typeof(GigyaUser).GetProperties();
                    gUser = new GigyaUser();
                    foreach (PropertyInfo property in properties)
                    {
                        property.SetValue(gUser, queryString[property.Name], null);
                    }

                    bool validUser = ValidateUserSignature(gUser.UID, gUser.signatureTimestamp, "0JPj1eH9tG7KpnW7uv6Fy+MspPStUUMpwdSfgFXN2ho=", gUser.UIDSignature);
                    if (!validUser)
                    {
                        gUser = null;
                        //throw exception
                    }
                }
            }
            catch (Exception ex)
            {
                // catch exception
            }
            return gUser;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="UID">pass the UID field returned by the "socialize.getUserInfo" API method response </param>
        /// <param name="timestamp">pass the signatureTimestamp field returned by the "socialize.getUserInfo" API method response </param>
        /// <param name="secret">your partner's "Secret Key", obtained from Gigya's website.</param>
        /// <param name="signature">pass the UIDSignature field returned by the "socialize.getUserInfo" API method response</param>
        /// <returns></returns>
        public static bool ValidateUserSignature(string UID, string signatureTimestamp, string secret, string UIDSignature)
        {
            return SigUtils.validateUserSignature(UID, signatureTimestamp, secret, UIDSignature);            
        }

        /// <summary>
        /// Inserts or Updates Gigya User into DB
        /// </summary>
        /// <param name="gUser"></param>
        /// <returns>0 if Error, 1 for Insert, 2 for Update</returns>
        public static int InsertOrUpdateGigyaUser(GigyaUser gUser)
        {
            int result = 0;
            if (gUser != null && gUser.UID.IsNotNullAndNotEmpty())
            {
                result = DBMapper.InsertOrUpdateGigyaUser(gUser);
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="gigyaUID"></param>
        /// <returns>Email/UserName/LoginName if user is registered or empty string</returns>
        public static string IsGigyaUserRegistered(string gigyaUID)
        {
            string email = string.Empty;
            email = DBMapper.IsGigyaUserRegistered(gigyaUID);
            return email;
        }

        public static bool RegisterGigyaUser(string gigyaUid, string email)
        {
            if (gigyaUid.IsNotNullAndNotEmpty() && email.IsNotNullAndNotEmpty() && StringUtils.IsValidEMailID(email))
            {
                return DBMapper.RegisterGigyaUser(gigyaUid, email);
            }
            return false;
        }

    }
}

/*
Twitter Return

provider=twitter
&UID=_gid_UGckGWIyQkSMeFXeNkSdMA%3d%3d
&timestamp=2010-10-24+23%3a07%3a12
&signature=weD%2fRfQlhovNq%2fb%2bxAACqDdWA3g%3d
&UIDSignature=vAWaRtwHDpjm7aME4W4m%2fIVjl%2fM3d
&signatureTimestamp=1287961632
&loginProvider=twitter
&loginProviderUID=44113020
&isLoggedIn=true
&isSiteUser=true
&isSiteUID=false
&nickname=pinalbhatt
&photoURL=http%3a%2f%2fa2.twimg.com%2fprofile_images%2f1090880686%2f27357_731775365_359_q_normal.jpg
&thumbnailURL=http%3a%2f%2fa2.twimg.com%2fprofile_images%2f1090880686%2f27357_731775365_359_q_normal.jpg
&birthDay=
&birthYear=
&birthMonth=
&gender=
&email=
&proxiedEmail=
&country=New+York
&city=
&state=
&zip=
&firstName=Pinal
&lastName=Bhatt
&profileURL=http%3a%2f%2ftwitter.com%2fpinalbhatt
&UIDSig=weD%2fRfQlhovNq%2fb%2bxAACqDdWA3g%3d

Facebook Return

provider=facebook
&UID=_gid_rAXR8Lh3J+rdxwmBkJ4Www==
&timestamp=2010-10-25 1:56:03
&signature=o2edcNfR4n7rxOkrNHoL+tqkWj8=
&UIDSignature=SlTgBcLfHpZGE4zTDS5kM1dbmsw=
&signatureTimestamp=1287971763
&loginProvider=facebook
&loginProviderUID=731775365
&isLoggedIn=true
&isSiteUser=true
&isSiteUID=false
&nickname=Pinal Bhatt
&photoURL=    http://profile.ak.fbcdn.net/hprofile-ak-nc4/hs171.ash2/41626_731775365_919_q.jpg
&thumbnailURL=http://profile.ak.fbcdn.net/hprofile-ak-nc4/hs171.ash2/41626_731775365_919_q.jpg
&birthDay=15
&birthYear=1974
&birthMonth=10
&gender=m
&email=pinalbhatt@gmail.com
&proxiedEmail=
&country=
&city=null
&state=
&zip=
&firstName=Pinal
&lastName=Bhatt
&profileURL=http://www.facebook.com/pinal.bhatt&UIDSig=o2edcNfR4n7rxOkrNHoL+tqkWj8=

Google 

provider=google
&UID=_gid_CAMlFyn MQ8Ja1rwI9ZIpGVC3UcOqF1qY BU6YP2aT4=
&timestamp=2010-10-25 02:03:02&signature=5V/dbBkD92d4AtgSbbpNMFUvkFo=
&UIDSignature= VwcENhpdH1wANxYHf5/0imjRE=
&signatureTimestamp=1287972182
&loginProvider=google
&loginProviderUID=116495447274977757345
&isLoggedIn=true
&isSiteUser=true
&isSiteUID=false
&nickname=Pinal Bhatt
&photoURL=
&thumbnailURL=
&birthDay=
&birthYear=
&birthMonth=
&gender=
&email=pinalbhatt@gmail.com
&proxiedEmail=
&country=
&city=
&state=
&zip=
&firstName=Pinal
&lastName=Bhatt
&profileURL=
&UIDSig=5V/dbBkD92d4AtgSbbpNMFUvkFo=

 Linked In
 
 provider=linkedin
&UID=_gid_/hE86Unz+0ABCMzCI1hLKa/LBpNlUGGeR5zYLEwbPXI=
&timestamp=2010-10-25 2:12:50
&signature=kxTJqv2bHDoI4zIG6uo4Tc2IQEQ=
&UIDSignature=rB9WChU5TNPdKWgD4jfUasYeWgo=
&signatureTimestamp=1287972770
&loginProvider=linkedin
&loginProviderUID=gRE0VKxkNI
&isLoggedIn=true
&isSiteUser=true
&isSiteUID=false
&nickname=Pinal Bhatt
&photoURL=
&thumbnailURL=
&birthDay=
&birthYear=
&birthMonth=
&gender=
&email=
&proxiedEmail=
&country=United States
&city=
&state=Greater New York City Area
&zip=
&firstName=Pinal
&lastName=Bhatt
&profileURL=http://www.linkedin.com/in/pinalbhatt&UIDSig=kxTJqv2bHDoI4zIG6uo4Tc2IQEQ=

*/